<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:insert="~{include :: header('编辑文章')}"/>
    <th:block th:insert="~{include :: summernote-css}"/>
    <th:block th:insert="~{include :: bootstrap-fileinput-css}" />
    
    <style>
        .hide-small-remove-btn .kv-file-remove {
            display: none !important;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-article-edit" th:object="${article}">
        <input id="id" name="id" type="hidden" th:field="*{id}"/>
        <input id="treeId" name="columnId" type="hidden" th:field="*{columnId}"/>
        <div class="form-group">
            <label class="col-sm-3 control-label ">所属栏目：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input class="form-control" type="text" onclick="selectDeptTree()" id="treeName"
                           th:readonly="readonly" th:field="*{columnName}">
                    <span class="input-group-addon"><i class="fa fa-search"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">文章标题：</label>
            <div class="col-sm-8">
                <input class="form-control" type="text" name="title" id="title" th:field="*{title}" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">摘要：</label>
            <div class="col-sm-8">
                <textarea type="text" name="description" class="form-control" th:rows="3" th:field="*{description}"
                          placeholder="请输摘要内容"></textarea>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">缩略图：</label>
            <input class="form-control" id="imageUrl" type="hidden" name="imageUrl" th:field="*{imageUrl}"/>
            <input class="form-control" id="imageName" type="hidden" name="imageName" th:field="*{imageName}"/>
            <div class="col-sm-3">
                <div class="file-loading">
                    <input id="imageFile" name="file" type="file">
                </div>
                <div id="errorBlock" style="color: red;"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">排序：</label>
            <div class="col-sm-8">
                <input class="form-control" type="text" name="sort" th:field="*{sort}" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">是否显示：</label>
            <div class="col-sm-9">
                <div class="radio-box" th:each="dict : ${@dict.getType('cms_show_hide')}">
                    <input type="radio" th:id="${dict.dictCode}" name="status" th:value="${dict.dictValue}"
                           th:field="*{status}" th:checked="${dict.default}">
                    <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">文章内容：</label>
            <div class="col-sm-9">
                <input id="content" name="content" th:field="*{content}" type="hidden">
                <div id="editor" class="summernote"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">备注：</label>
            <div class="col-sm-8">
                <textarea type="text" name="remark" class="form-control" th:field="*{remark}" th:rows="3"
                          placeholder="请输入文本"></textarea>
            </div>
        </div>
    </form>
</div>
<th:block th:insert="~{include :: footer}"/>
<th:block th:insert="~{include :: summernote-js}"/>
<th:block th:insert="~{include :: bootstrap-fileinput-js}" />
<script type="text/javascript" th:inline="javascript">
    var prefix = ctx + "cms/article";
    $(function () {
        $('.summernote').summernote({
            placeholder: '请输入文章内容',
            height: 320,
            lang: 'zh-CN',
            followingToolbar: false,
            dialogsInBody: true,
            callbacks: {
                onImageUpload: function (files) {
                    sendFile(files[0], this);
                }
            }
        });
        var content = $("#content").val();
        $('#editor').summernote('code', content);


        // 初始化已有文件预览
        var initialFile = $("#imageUrl").val();
        var fileInputConfig = {
            uploadUrl: prefix + '/uploadCMS',
            maxFileCount: 1,
            autoReplace: true,
            showUpload: true,
            showRemove: true,
            showCaption: true,
            showPreview: true,
            showClose: false,
            browseClass: "btn btn-primary",
            browseLabel: "选择文件",
            browseIcon: '<i class="fa fa-file-music-o"></i> ',
            removeClass: "btn btn-danger",
            removeLabel: "移除",
            removeIcon: '<i class="fa fa-trash"></i> ',
            uploadClass: "btn btn-success",
            uploadLabel: "上传",
            uploadIcon: '<i class="fa fa-upload"></i> ',
            allowedFileExtensions: ["bmp", "gif", "jpg", "jpeg", "png"],
            previewFileIcon: '<i class="fa fa-file-audio-o"></i>',
            maxFileSize: 20000, // 20MB
            msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许的最大大小 {maxSize} KB。',
            msgFilesTooLess: '您必须至少选择 {n} 个文件来上传。',
            msgInvalidFileExtension: '不支持的文件类型 "{name}"。只允许 "{extensions}" 类型的文件。',
            elErrorContainer: '#errorBlock',
            previewClass: 'hide-small-remove-btn'
        };

        // 如果有已存在的文件，添加初始预览配置
        if (initialFile && initialFile.length > 0) {
            // 提取文件名
            var fileName = initialFile.split('/').pop();

            // 直接使用URL回显，保持组件原生样式
            fileInputConfig.initialPreview = [initialFile];
            fileInputConfig.initialPreviewAsData = true; // 关键配置：将URL视为数据
            fileInputConfig.initialPreviewConfig = [
                {
                    caption: fileName,
                    type: 'image',
                    size: 0, // 可从服务器获取实际大小
                    url: prefix + '/deleteFile', // 删除文件的URL
                    key: 1,
                    extra: {id: $('#id').val(), field: 'imageUrl'},
                    downloadUrl: initialFile
                }
            ];
            fileInputConfig.overwriteInitial = true;
        }

        // 初始化文件上传组件并缓存实例
        var $fileInput = $("#imageFile").fileinput(fileInputConfig);

        // 绑定文件清空事件（处理初始预览和新上传文件的移除）
        $fileInput.on('fileclear', function() {
            $("#imageUrl").val('');
            $("#imageName").val('');
        });

        // 绑定文件上传成功事件
        $fileInput.on('fileuploaded', function(event, data) {
            var rsp = data.response;
            $("#imageUrl").val(rsp.url);
            $("#imageName").val(rsp.newFileName);
            $.modal.alertSuccess("文件上传成功!");
        });

        // 绑定文件上传失败事件
        $fileInput.on('fileuploaderror', function(event, data) {
            var response = data.response;
            console.log('上传错误信息:', response);
            $.modal.alertError("文件上传失败: " + (response ? response.message : '未知错误'));
        });

        // 绑定文件验证错误事件
        $fileInput.on('fileerror', function(event, data, msg) {
            $.modal.alertWarning(msg);
        });
    })

    // 上传文件
    function sendFile(file, obj) {
        var data = new FormData();
        data.append("file", file);
        $.ajax({
            type: "POST",
            url: ctx + "common/cms/upload",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $(obj).summernote('editor.insertImage', result.url, result.fileName);
                } else {
                    $.modal.alertError(result.msg);
                }
            },
            error: function (error) {
                $.modal.alertWarning("图片上传失败。");
            }
        });
    }

    $("#form-article-edit").validate({
        onkeyup: false,
        rules: {
            outLink: {
                required: true
            },
            sort: {
                digits: true
            }
        },
        messages: {
            "name": {
                remote: "栏目名称已经存在"
            }
        },
        focusCleanup: true
    });

    function selectDeptTree() {
        var options = {
            title: '栏目选择',
            width: "380",
            url: prefix + "/selectColumnTree?columnId=" + $("#treeId").val(),
            callBack: doSubmit
        };
        $.modal.openOptions(options);
    }

    function doSubmit(index, layero) {
        var body = $.modal.getChildFrame(index);
        $("#treeId").val(body.find('#treeId').val());
        $("#treeName").val(body.find('#treeName').val());
        $.modal.close(index);
    }

    function submitHandler() {
        if ($.validate.form()) {
            var sHTML = $('.summernote').summernote('code');
            $("#content").val(sHTML);
            $.operate.save(prefix + "/editArticle", $('#form-article-edit').serializeArray());
        }
    }
    
</script>
</body>
</html>
